/*
 * The COM Server that serves the Client on the COM Port 
*/

package com.costeaalex.blueserver.comm;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.comm.*;

import com.costeaalex.blueserver.communication.CommunicationManager;

public class COMServer implements CommunicationManager
	{
	
	private InputStream inStream;
	private OutputStream outStream;
	private CommPort cPL;
	private CommPortIdentifier cPI;
	private int outputBufferSize=4096;
	
	public COMServer(CommPort cP)
		{
		System.out.println("\nCOMServer "+cP.getName()+"\n");
		try
			{
			cPI=CommPortIdentifier.getPortIdentifier(cP.getName());
			} 
		catch (NoSuchPortException e)
			{
			e.printStackTrace();
			}
		try
			{
			cPL=cPI.open("BlueRemoteServer",5000);
			outputBufferSize=cPL.getOutputBufferSize();
			} 
		catch (PortInUseException e)
			{
			e.printStackTrace();
			}
		}
	
	public void start()
		{
		try
			{
			inStream=cPL.getInputStream();
			} 
		catch (IOException e)
			{
			e.printStackTrace();
			}
		
		try
			{
			outStream=cPL.getOutputStream();
			} 
		catch (IOException e)
			{
			e.printStackTrace();
			}
		}
	
	public void send(byte[] data)
		{
		try
			{
			outStream.write(data);
			outStream.flush();
			}
		catch (IOException e)
			{
			e.printStackTrace();
			}
		}
	
	public void send(int data)
		{
		try
			{
			outStream.write(data);
			outStream.flush();
			} 
		catch (IOException e)
			{
			e.printStackTrace();
			}
		//System.out.println("Sent byte");
		}
	
	public int receive()
		{
		try
			{
			return inStream.read();
			} 
		catch (IOException e)
			{
			e.printStackTrace();
			}
		return 0;
		}
	
	public int receiveBlock(byte[] received)
		{
		try
			{
			return inStream.read(received);
			} 
		catch (IOException e)
			{
			e.printStackTrace();
			return -1;
			}
		}
	
	public void stop()
		{
		cPL.close();
		System.out.println("Stopped server");
		}

	public int getOutputBufferSize()
		{
		return outputBufferSize;
		}

	}
